package frank.zou.fit.casestudy.order;

import java.io.InputStreamReader;

import org.drools.RuleBase;
import org.drools.RuleBaseFactory;
import org.drools.WorkingMemory;

import org.drools.compiler.PackageBuilder;

public class PricingEngine {

  private static final String RULES="frank/zou/fit/casestudy/order/discount-rules.drl";
//	private static final String RULES="BusinessRules.drl";	
  private static RuleBase businessRules;

//  private static void loadRules() throws Exception{
//    if (businessRules==null){			
//      businessRules = RuleBaseLoader.
//         loadFromUrl(PricingEngine.class.getResource(RULES));
//    }
//  }	
  

  private static void loadRules() throws Exception{
	    if (businessRules==null){

	    	businessRules = RuleBaseFactory.newRuleBase();
	    	
	    	PackageBuilder builder = new PackageBuilder();
	    	builder.addPackageFromDrl(new InputStreamReader
	    			(PricingEngine.class.getClassLoader().getSystemResourceAsStream(RULES)));
	    	
	    	businessRules.addPackage(builder.getPackage());
	    		      
	    }
	  }	  

  public static void applyDiscount(WholeSaleOrder order) throws Exception{
    loadRules();             
    WorkingMemory workingMemory = businessRules.newWorkingMemory( );
    workingMemory.assertObject(order);       
    workingMemory.fireAllRules();		
  }
}